package nl.hanze.designpatterns.db;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

public class RowIterator<T> implements Iterator<T> {
    Class<T> tClass;
    ResultSet resultSet;

    protected RowIterator(Class<T> tClass, ResultSet resultSet) {
        this.tClass = tClass;
        this.resultSet = resultSet;
    }


    @Override
	public boolean hasNext() {
        boolean hasNext = false;
        try {
            hasNext = resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return hasNext;
	}

	@Override
	public T next() {

        try {
            T t = tClass.newInstance();
            Field[] fields = tClass.getFields();
            for( Field field : fields) {
                String fieldName = field.getName();
                Object value = resultSet.getObject(fieldName);
                if (value != null) {
                    field.set(t, value);
                }
            }
            return t;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}
